package com.design.config;

import com.alibaba.fastjson.JSONObject;
import com.design.utils.JwtOperator;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Slf4j
public class MyInterceptor implements MethodInterceptor {

    private final static String logStr = "\r\n[请求URL:{}]\r\n[请求参数:{}]\r\n[返回结果:{}]";

    private JwtOperator jwtOperator;

    public MyInterceptor(JwtOperator jwtOperator){
        this.jwtOperator = jwtOperator;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method[] methods = Object.class.getMethods();
        for (Method m : methods) {
            if (invocation.getMethod().equals(m)) {
                return null;
            }
        }
        List<Object> parameters = getArguments(invocation);
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        // 登录校验
        if(!(String.valueOf(httpServletRequest.getRequestURL()).contains("/login")
                || String.valueOf(httpServletRequest.getRequestURL()).contains("/sensor"))){
            String token = httpServletRequest.getHeader("token");
            if(StringUtils.isEmpty(token) || !jwtOperator.validateToken(token)){
                throw new CommonException("401", "未登录");
            }
        }
        Object object = invocation.proceed();
        String result = JSONObject.toJSONString(object);
        log.info(logStr, httpServletRequest.getRequestURL(), parameters, result);
        return object;
    }

    protected List<Object> getArguments(MethodInvocation invocation) {
        Object[] arguments = invocation.getArguments();
        if (arguments.length == 0) {
            return Collections.emptyList();
        }
        return Arrays.asList(arguments);
    }
}

